using Framework.Table;
using UnityEngine;

namespace Framework.UI
{
	public partial class ActorShowFrame : UIFrame
	{
        protected override string ActivedScene => "scene_actor_show";

        unsafe UnitTableItem* _role_model_item;
        YooAsset.AssetHandle _role_model_handle;
        GameObject _role_model;
        protected override void OnFrameOpen()
        {
            var unitTable = TableManager.GetTable<UnitTable>();
            unsafe
            {
                _role_model_item = unitTable.GetItem(MainPlayer.RoleId);

                if (_role_model_item != null)
                {
                    var model = unitTable.getStringValue(_role_model_item->_ActorModel_pos, _role_model_item->_ActorModel_count);
                    _role_model_handle = YooAsset.YooAssets.LoadAssetSync(model);
                    if (_role_model_handle.AssetObject is GameObject model_template)
                    {
                        _role_model = Object.Instantiate(model_template, null, false);
                    }
                    var roleName = unitTable.getStringValue(_role_model_item->_Name_pos, _role_model_item->_Name_count);
                    this.JobName.text = roleName;
                }
            }
            this.PlayerName.text = MainPlayer.PlayerName;
            EventDispatchManager.Instance.AddEvent(EventId.Game.EVENT_ROOM_CREATED, OnEventRoomCreated);
        }

        void OnEventRoomCreated(IEventArgv eventArgv)
        {
            YooAsset.YooAssets.LoadSceneAsync("scene_room");
        }

        protected override void OnFrameClose()
        {
            EventDispatchManager.Instance.RemoveEvent(EventId.Game.EVENT_ROOM_CREATED, OnEventRoomCreated);
            Object.Destroy(_role_model);
            _role_model = null;
            _role_model_handle.Dispose();
            _role_model_handle = null;
            unsafe
            {
                _role_model_item = null;
            }
        }

        void OnBtnCreateRoomClicked()
		{
            //Add Your Code Here
            UIFrameManager.Instance.OpenFrame<CreateRoomEditFrame>(layer: UILayer.Top);
        }

		void OnBtnBackToLoginClicked()
		{
			//Add Your Code Here
			EventDispatchManager.Instance.SendEvent(EventId.Game.EVENT_PLAYER_OUTLOGIN);
            YooAsset.YooAssets.LoadSceneAsync("login_scene");
		}
	}
}
